import React, { useEffect, useState, useMemo, memo } from 'react';
import { message } from 'antd';
import { initTooltip } from '@/components/Charts/ChartsConfig';
import createG2 from '../G2Create';

import IChartsProps from '../ICharts';
import { onShowTooltip, setDataPie } from '../ChartsConfig';

const styles = require('../index.less');

const Pie: React.FC<IChartsProps> = memo((props) => {

  const { onSelect, showDataDown, width, height, drillsIcon, filterConfigs } = props;
  const [records, setRecords] = useState<Array<any>>([]);


  const getValue = (event: any) => {
    const values = [];
    values.push(event.data.data);
    setRecords(values);
    return values;
  };
  /**
   * 记录点击后的记录值
   * @param event
   * @param chart
   * @param canvas
   */
  const chartClick = (event: any) => {
    const values = getValue(event);
    if(onSelect){
      onSelect(values)
    }
  };
  /**
   * 设置数据的格式
   */
  const setValueFormat = (total: any) => {
    const formatter = (ivalue: any) => {
      return `${ivalue}(${Math.floor((ivalue / total) * 100 * Math.pow(10, 2)) / Math.pow(10, 2)}%)`;
    };
    return { value: { formatter } };
  };

  /**
   * 图表渲染
   * @param chart
   * @param configs
   */
  const g2Create = (chart: any, configs: any) => {
    const { color, chartStyles } = props.configs;
    const { items } = color;
    const colors: Array<string> = items.length > 0 ? Object.values(items[0].config.values) : [];
    const groups: Array<string> = filterConfigs.groups.filter((v: string) => v);
    // 维度字段
    const name = groups[groups.length - 1];
    const data: Array<any> = setDataPie(props);
    let total = 0;
    if (data.length > 0) {
      total = data.map((v: any) => v.value).reduce((f: any, s: any) => f + s);
    }
    chart.on('point:click', (ev: any) => {
      ev.data && chartClick(ev);
    });
    // const canvas = chart.get('canvas')
    //
    // canvas._attrs.el.onclick = function (event: any) {
    //   chartClick(event, chart, canvas)
    // };
    configs.onEvent(chart);

    // 去掉轴标签
    chart.axis(false);
    // 展示图例
    if (!chartStyles.legend.showLegend) {
      chart.legend(false);
    }
    if (data && data.length) {
      const names = Array.from(new Set(data.map(v => v[name])));
      if (names && JSON.stringify(names).length > 70) {
        chart.legend(false);
      }
    }
    const $chart = chart.interval().position(configs.position);
    // 展示标签(添加饼图文本)
    if (chartStyles.label.showLabel) {
      $chart.label('const', () => {
        return {
          content: (obj: any) => {
            const { value } = obj;
            return `${obj[name]}:${value}(${Math.floor(value / total * 100 * Math.pow(10, 2)) / Math.pow(10, 2)}%)`;
          },
        };
      });
    }
    // 开启饼状图
    chart.coordinate('theta', {
      radius: 0.75,
    });
    const models = new Set();
    data.forEach(v => {
      models.add(v[name]);
    });
    if (colors && colors.length && models.size <= colors.length) {
      $chart.color(name, colors).adjust('stack');
    } else {
      $chart.color(name).adjust('stack');
    }
    // 添加点击样式
    chart.interaction('pie-select', {
      startEvent: 'tap',
      animate: {
        duration: 300,
        easing: 'backOut',
      },
      cancelable: true,
    });
    chart.source(data, setValueFormat(total));
    chart.render();
  };
  let G2Create = createG2(g2Create);
  useEffect(() => {
    setRecords([]);
    G2Create = createG2(g2Create);

  }, [props]);

  /**
   * 下钻
   */
  const dataDown = () => {
    if (records.length === 0) {
      message.info('请选择', 2);
      return;
    }
    showDataDown(records);
  };


  /**
   * 配置重构
   */
  const setConfigs = () => {
    const chartOnEvent = (chart: any) => {
      chart.interaction('element-single-selected'); // 使用 active-region 交互行为

      // tooltip 显示时触发
      chart.on('tooltip:show', (ev: { x: any, y: any, title: string, items: any[], tooltip: any }) => {
        onShowTooltip(props, ev);
      });
    };
    return {
      tooltip: initTooltip(props),
      position: `const*value`,
      onEvent: chartOnEvent,
    };
  };


  const configs = setConfigs();
  const G2Chart = useMemo(() => <G2Create
    width={width}
    height={height}
    configs={configs}
  />, [props]);
  return (
    <div>
      {showDataDown ? <div className={styles.drillBody}>
        {drillsIcon(dataDown)}
      </div> : null}

      {G2Chart}
    </div>
  );
});
export default Pie;
